package com.doublethread.easymart.modules.order.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doublethread.easymart.common.exception.OrderException;
import com.doublethread.easymart.common.exception.ProductException;
import com.doublethread.easymart.common.exception.UserException;
import com.doublethread.easymart.common.result.PageResult;
import com.doublethread.easymart.modules.cart.service.CartService;
import com.doublethread.easymart.modules.cart.vo.CartVO;
import com.doublethread.easymart.modules.order.dto.*;
import com.doublethread.easymart.modules.order.entity.Order;
import com.doublethread.easymart.modules.order.entity.OrderItem;
import com.doublethread.easymart.modules.order.mapper.OrderItemMapper;
import com.doublethread.easymart.modules.order.mapper.OrderMapper;
import com.doublethread.easymart.modules.order.service.OrderService;
import com.doublethread.easymart.modules.order.vo.OrderItemVO;
import com.doublethread.easymart.modules.order.vo.OrderStatisticsVO;
import com.doublethread.easymart.modules.order.vo.OrderVO;
import com.doublethread.easymart.modules.product.entity.Product;
import com.doublethread.easymart.modules.product.mapper.ProductMapper;
import com.doublethread.easymart.modules.user.entity.User;
import com.doublethread.easymart.modules.user.entity.UserAddress;
import com.doublethread.easymart.modules.user.mapper.UserMapper;
import com.doublethread.easymart.modules.user.service.AddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 订单服务实现类
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private AddressService addressService;

    // ==================== 公开接口（用户端）实现 ====================

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderVO createOrder(Long userId, OrderCreateDTO orderCreateDTO) {
        log.info("创建订单");

        // 1. 验证用户存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            UserException.userNotFound();
        }

        // 2. 获取订单商品数据
        List<OrderItemData> orderItemDataList = new ArrayList<>();
        if (orderCreateDTO.getCartIds() != null && !orderCreateDTO.getCartIds().isEmpty()) {
            // 从购物车下单
            List<CartVO> cartItems = cartService.getSelectedCartItems(userId, orderCreateDTO.getCartIds());
            if (cartItems.isEmpty()) {
                OrderException.cartItemNotFound();
            }
            // 验证商品库存和状态
            for (CartVO cartItem : cartItems) {
                if (!cartItem.getIsValid()) {
                    ProductException.outOfStock();
                }
            }
            // 转换为订单商品数据
            orderItemDataList = cartItems.stream()
                    .map(cartItem -> new OrderItemData(
                            cartItem.getProductId(),
                            cartItem.getProductName(),
                            cartItem.getProductImage(),
                            cartItem.getCurrentPrice(),
                            cartItem.getQuantity(),
                            cartItem.getSubtotal()
                    ))
                    .toList();

        } else if (orderCreateDTO.getOrderItems() != null && !orderCreateDTO.getOrderItems().isEmpty()) {
            // 立即购买
            for (OrderCreateDTO.OrderItemDTO itemDTO : orderCreateDTO.getOrderItems()) {
                // 查询商品信息
                Product product = productMapper.selectById(itemDTO.getProductId());
                if (product == null || product.getStatus() != 1) {
                    ProductException.productNotFound();
                }
                // 验证库存
                if (product.getStock() < itemDTO.getQuantity()) {
                    ProductException.outOfStock();
                }
                // 计算价格
                BigDecimal unitPrice = product.getPrice();
                BigDecimal totalPrice = unitPrice.multiply(new BigDecimal(itemDTO.getQuantity()));

                // 添加到订单商品数据列表
                orderItemDataList.add(new OrderItemData(
                        product.getId(),
                        product.getName(),
                        product.getMainImage(),
                        unitPrice,
                        itemDTO.getQuantity(),
                        totalPrice
                ));
            }
        } else {
            OrderException.cartItemNotFound();
        }

        // 3. 计算订单金额
        BigDecimal totalAmount = orderItemDataList.stream()
                .map(OrderItemData::getTotalPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 4. 获取收货地址信息
        UserAddress address = addressService.checkAddressOwnership(userId, orderCreateDTO.getAddressId());
        String fullAddress = addressService.buildFullAddress(address);

        // 5. 创建订单 - 使用Builder模式
        Order order = Order.builder()
                .orderNo(generateOrderNo())
                .userId(userId)
                .totalAmount(totalAmount)
                .actualAmount(totalAmount) // 暂不考虑优惠
                .paymentType(orderCreateDTO.getPaymentType())
                .paymentStatus(0) // 未支付
                .deliveryStatus(0) // 未发货
                .status(1) // 待支付
                .receiverName(address.getReceiverName())
                .receiverPhone(address.getReceiverPhone())
                .receiverAddress(fullAddress)
                .remark(orderCreateDTO.getRemark()) // 使用用户输入的备注
                .build();

        this.save(order);

        // 6. 扣减商品库存（下单时预占库存）
        for (OrderItemData itemData : orderItemDataList) {
            Product product = productMapper.selectById(itemData.getProductId());
            if (product != null) {
                // 扣减库存
                Product updateProduct = new Product();
                updateProduct.setId(product.getId());
                updateProduct.setStock(product.getStock() - itemData.getQuantity());
                productMapper.updateById(updateProduct);

                log.info("扣减商品库存");
            }
        }

        // 7. 创建订单项 - 使用Builder模式
        List<OrderItem> orderItems = orderItemDataList.stream()
                .map(itemData -> OrderItem.builder()
                        .orderId(order.getId())
                        .productId(itemData.getProductId())
                        .productName(itemData.getProductName())
                        .productImage(itemData.getProductImage())
                        .unitPrice(itemData.getUnitPrice())
                        .quantity(itemData.getQuantity())
                        .totalPrice(itemData.getTotalPrice())
                        .status(1)
                        .build())
                .toList();

        if (!orderItems.isEmpty()) {
            for (OrderItem orderItem : orderItems) {
                orderItemMapper.insert(orderItem);
            }
        }

        // 7. 如果是从购物车下单，删除购物车中的商品
        if (orderCreateDTO.getCartIds() != null && !orderCreateDTO.getCartIds().isEmpty()) {
            cartService.removeCartItems(userId, orderCreateDTO.getCartIds());
        }

        log.info("订单创建成功");
        return convertToOrderVO(order);
    }

    @Override
    public PageResult<OrderVO> getUserOrderList(Long userId, OrderQueryDTO queryDTO) {
        log.info("获取用户订单列表");

        // 构建查询条件
        LambdaQueryWrapper<Order> queryWrapper = buildQueryWrapper(queryDTO);
        queryWrapper.eq(Order::getUserId, userId);

        // 分页查询
        Page<Order> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        Page<Order> orderPage = this.page(page, queryWrapper);

        // 使用PageResult.of方法进行转换
        return PageResult.of(orderPage, this::convertToOrderVO);
    }

    @Override
    public OrderVO getOrderById(Long userId, Long orderId) {
        log.info("获取订单详情");

        Order order = this.getById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            OrderException.orderNotFound();
        }

        return convertToOrderVOWithItems(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(Long userId, Long orderId, OrderCancelDTO cancelDTO) {
        log.info("取消订单");

        Order order = this.getById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            OrderException.orderNotFound();
        }

        // 检查订单状态是否可以取消
        if (order.getStatus() != 1) { // 只有待支付状态可以取消
            OrderException.orderCannotCancel();
        }

        // 更新订单状态为已取消
        Order updateOrder = new Order();
        updateOrder.setId(orderId);
        updateOrder.setStatus(0); // 已取消
        updateOrder.setRemark(cancelDTO.getReason());
        this.updateById(updateOrder);

        // 恢复库存
        restoreProductStock(orderId);

        log.info("订单取消成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmReceive(Long userId, Long orderId) {
        log.info("确认收货");

        Order order = this.getById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            OrderException.orderNotFound();
        }

        // 检查订单状态是否可以确认收货
        if (order.getStatus() != 3) { // 只有待收货状态可以确认收货
            OrderException.orderCannotReceive();
        }

        // 更新订单状态为已完成
        Order updateOrder = new Order();
        updateOrder.setId(orderId);
        updateOrder.setStatus(4); // 已完成
        updateOrder.setDeliveryStatus(2); // 已收货
        updateOrder.setReceiveTime(LocalDateTime.now());
        this.updateById(updateOrder);

        log.info("确认收货成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void payOrder(Long userId, Long orderId) {
        log.info("支付订单");

        Order order = this.getById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            OrderException.orderNotFound();
        }

        // 检查订单状态是否可以支付
        if (order.getStatus() != 1) { // 只有待支付状态可以支付
            OrderException.orderCannotPay();
        }

        // 更新订单状态为待发货
        Order updateOrder = new Order();
        updateOrder.setId(orderId);
        updateOrder.setStatus(2); // 待发货
        updateOrder.setPaymentStatus(1); // 已支付
        updateOrder.setPaymentTime(LocalDateTime.now());
        this.updateById(updateOrder);

        // 支付成功后删除对应的购物车商品
        // 通过订单备注字段获取购物车ID信息
        if (StringUtils.hasText(order.getRemark()) && order.getRemark().startsWith("cart_ids:")) {
            try {
                String cartIdsJson = order.getRemark().substring("cart_ids:".length());
                List<Long> cartIds = JSON.parseArray(cartIdsJson, Long.class);
                if (cartIds != null && !cartIds.isEmpty()) {
                    cartService.removeCartItems(userId, cartIds);
                    log.info("支付成功，已删除购物车商品: userId={}, cartIds={}", userId, cartIds);
                }
            } catch (Exception e) {
                log.warn("删除购物车商品失败，但不影响支付: userId={}, orderId={}, error={}",
                        userId, orderId, e.getMessage());
            }
        }

        log.info("订单支付成功");
    }

    @Override
    public PageResult<OrderVO> getAdminOrderList(OrderQueryDTO queryDTO) {
        log.info("管理端查询订单列表");

        // 构建查询条件
        LambdaQueryWrapper<Order> queryWrapper = buildQueryWrapper(queryDTO);

        // 分页查询
        Page<Order> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        Page<Order> orderPage = this.page(page, queryWrapper);

        // 使用PageResult.of方法进行转换
        return PageResult.of(orderPage, this::convertToOrderVO);
    }

    @Override
    public OrderVO getAdminOrderById(Long orderId) {
        log.info("管理端获取订单详情");

        Order order = this.getById(orderId);
        if (order == null) {
            OrderException.orderNotFound();
        }

        OrderVO orderVO = convertToOrderVO(order);

        // 获取订单项列表
        List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderId, orderId));
        List<OrderItemVO> orderItemVOs = orderItems.stream()
                .map(this::convertToOrderItemVO)
                .toList();
        orderVO.setOrderItems(orderItemVOs);

        return orderVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deliverOrder(Long orderId, OrderDeliveryDTO deliveryDTO) {
        log.info("订单发货");

        Order order = this.getById(orderId);
        if (order == null) {
            OrderException.orderNotFound();
        }

        // 检查订单状态是否可以发货
        if (order.getStatus() != 2) { // 只有待发货状态可以发货
            OrderException.orderCannotDeliver();
        }

        // 更新订单状态为待收货（整个订单一起发货）
        Order updateOrder = new Order();
        updateOrder.setId(orderId);
        updateOrder.setStatus(3); // 待收货
        updateOrder.setDeliveryStatus(1); // 已发货
        updateOrder.setDeliveryTime(LocalDateTime.now());
        this.updateById(updateOrder);

        // 发货时增加商品销量
        List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderId, orderId));

        for (OrderItem orderItem : orderItems) {
            Product product = productMapper.selectById(orderItem.getProductId());
            if (product != null) {
                // 增加销量
                Product updateProduct = new Product();
                updateProduct.setId(product.getId());
                updateProduct.setSales(product.getSales() + orderItem.getQuantity());
                productMapper.updateById(updateProduct);

                log.info("增加商品销量: productId={}, quantity={}, newSales={}",
                        product.getId(), orderItem.getQuantity(), updateProduct.getSales());
            }
        }

        log.info("订单发货成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void adminCancelOrder(Long orderId, OrderCancelDTO cancelDTO) {
        log.info("管理端取消订单");

        Order order = this.getById(orderId);
        if (order == null) {
            OrderException.orderNotFound();
        }

        // 检查订单状态是否可以取消
        if (order.getStatus() == 0 || order.getStatus() == 4) { // 已取消或已完成的订单不能再取消
            OrderException.orderCannotCancel();
        }

        // 更新订单状态为已取消
        Order updateOrder = new Order();
        updateOrder.setId(orderId);
        updateOrder.setStatus(0); // 已取消
        updateOrder.setRemark(cancelDTO.getReason());
        this.updateById(updateOrder);

        // 恢复库存
        restoreProductStock(orderId);

        log.info("管理端取消订单成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderRemark(Long orderId, OrderRemarkDTO remarkDTO) {
        log.info("更新订单备注");

        Order order = this.getById(orderId);
        if (order == null) {
            OrderException.orderNotFound();
        }

        // 更新订单备注
        Order updateOrder = new Order();
        updateOrder.setId(orderId);
        updateOrder.setRemark(remarkDTO.getRemark());
        this.updateById(updateOrder);

        log.info("订单备注更新成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderStatus(Long orderId, OrderUpdateStatusDTO statusDTO) {
        log.info("更新订单状态");

        Order order = this.getById(orderId);
        if (order == null) {
            OrderException.orderNotFound();
        }

        // 更新订单状态
        Order updateOrder = new Order();
        updateOrder.setId(orderId);
        updateOrder.setStatus(statusDTO.getStatus());
        this.updateById(updateOrder);

        log.info("订单状态更新成功");
    }

    @Override
    public OrderStatisticsVO getOrderStatistics(LocalDate startDate, LocalDate endDate) {
        log.info("获取订单统计信息: startDate={}, endDate={}", startDate, endDate);

        // 构建查询条件
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<Order>()
                .eq(Order::getIsDeleted, 0);

        if (startDate != null && endDate != null) {
            queryWrapper.between(Order::getCreateTime, startDate.atStartOfDay(), endDate.plusDays(1).atStartOfDay());
        }

        // 查询所有订单
        List<Order> orders = this.list(queryWrapper);

        // 统计各种数据
        long totalOrders = orders.size();
        long todayOrders = orders.stream()
                .filter(order -> order.getCreateTime().toLocalDate().equals(LocalDate.now()))
                .count();
        long pendingPayment = orders.stream()
                .filter(order -> order.getStatus() == 1)
                .count();
        long pendingDelivery = orders.stream()
                .filter(order -> order.getStatus() == 2)
                .count();
        long pendingReceive = orders.stream()
                .filter(order -> order.getStatus() == 3)
                .count();
        long completedOrders = orders.stream()
                .filter(order -> order.getStatus() == 4)
                .count();
        long cancelledOrders = orders.stream()
                .filter(order -> order.getStatus() == 0)
                .count();

        BigDecimal totalAmount = orders.stream()
                .map(Order::getTotalAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        BigDecimal todayAmount = orders.stream()
                .filter(order -> order.getCreateTime().toLocalDate().equals(LocalDate.now()))
                .map(Order::getTotalAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        BigDecimal avgOrderAmount = totalOrders > 0 ?
                totalAmount.divide(BigDecimal.valueOf(totalOrders), 2, RoundingMode.HALF_UP) :
                BigDecimal.ZERO;

        // 使用Builder模式构建统计VO
        return OrderStatisticsVO.builder()
                .totalOrders(totalOrders)
                .todayOrders(todayOrders)
                .pendingPayment(pendingPayment)
                .pendingDelivery(pendingDelivery)
                .pendingReceive(pendingReceive)
                .completedOrders(completedOrders)
                .cancelledOrders(cancelledOrders)
                .totalAmount(totalAmount)
                .todayAmount(todayAmount)
                .avgOrderAmount(avgOrderAmount)
                .build();
    }

    @Override
    public void handleExpiredOrders() {
        log.info("处理过期订单");

        // 查询过期的待支付订单
        List<Order> expiredOrders = this.list(new LambdaQueryWrapper<Order>()
                .eq(Order::getStatus, 1) // 待支付
                .lt(Order::getExpireTime, LocalDateTime.now()));

        for (Order order : expiredOrders) {
            // 更新订单状态为已过期
            Order updateOrder = new Order();
            updateOrder.setId(order.getId());
            updateOrder.setStatus(5); // 已过期
            this.updateById(updateOrder);

            // 恢复库存
            restoreProductStock(order.getId());
        }

        log.info("处理过期订单完成");
    }

    @Override
    public void autoConfirmReceive() {
        log.info("自动确认收货");

        // 查询发货超过7天且状态为待收货的订单
        LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(7);
        List<Order> ordersToConfirm = this.list(new LambdaQueryWrapper<Order>()
                .eq(Order::getStatus, 3) // 待收货
                .le(Order::getDeliveryTime, sevenDaysAgo));

        for (Order order : ordersToConfirm) {
            // 自动确认收货
            Order updateOrder = new Order();
            updateOrder.setId(order.getId());
            updateOrder.setStatus(4); // 已完成
            updateOrder.setDeliveryStatus(2); // 已收货
            updateOrder.setReceiveTime(LocalDateTime.now());
            this.updateById(updateOrder);
        }

        log.info("自动确认收货完成");
    }


    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<Order> buildQueryWrapper(OrderQueryDTO queryDTO) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();

        // 订单号搜索
        if (StringUtils.hasText(queryDTO.getOrderNo())) {
            queryWrapper.like(Order::getOrderNo, queryDTO.getOrderNo());
        }

        // 用户ID筛选
        if (queryDTO.getUserId() != null) {
            queryWrapper.eq(Order::getUserId, queryDTO.getUserId());
        }

        // 收货人手机号搜索
        if (StringUtils.hasText(queryDTO.getReceiverPhone())) {
            queryWrapper.like(Order::getReceiverPhone, queryDTO.getReceiverPhone());
        }

        // 订单状态筛选
        if (queryDTO.getStatus() != null) {
            queryWrapper.eq(Order::getStatus, queryDTO.getStatus());
        }

        // 支付状态筛选
        if (queryDTO.getPaymentStatus() != null) {
            queryWrapper.eq(Order::getPaymentStatus, queryDTO.getPaymentStatus());
        }

        // 发货状态筛选
        if (queryDTO.getDeliveryStatus() != null) {
            queryWrapper.eq(Order::getDeliveryStatus, queryDTO.getDeliveryStatus());
        }

        // 支付方式筛选
        if (queryDTO.getPaymentType() != null) {
            queryWrapper.eq(Order::getPaymentType, queryDTO.getPaymentType());
        }

        // 订单金额区间筛选
        if (queryDTO.getMinAmount() != null) {
            queryWrapper.ge(Order::getTotalAmount, queryDTO.getMinAmount());
        }
        if (queryDTO.getMaxAmount() != null) {
            queryWrapper.le(Order::getTotalAmount, queryDTO.getMaxAmount());
        }

        // 时间区间筛选
        if (queryDTO.getStartTime() != null) {
            queryWrapper.ge(Order::getCreateTime, queryDTO.getStartTime());
        }
        if (queryDTO.getEndTime() != null) {
            queryWrapper.le(Order::getCreateTime, queryDTO.getEndTime());
        }

        // 排序处理
        if ("totalAmount".equals(queryDTO.getSortBy())) {
            if ("desc".equals(queryDTO.getSortOrder())) {
                queryWrapper.orderByDesc(Order::getTotalAmount);
            } else {
                queryWrapper.orderByAsc(Order::getTotalAmount);
            }
        } else if ("paymentTime".equals(queryDTO.getSortBy())) {
            if ("desc".equals(queryDTO.getSortOrder())) {
                queryWrapper.orderByDesc(Order::getPaymentTime);
            } else {
                queryWrapper.orderByAsc(Order::getPaymentTime);
            }
        } else {
            // 默认按创建时间排序
            if ("desc".equals(queryDTO.getSortOrder())) {
                queryWrapper.orderByDesc(Order::getCreateTime);
            } else {
                queryWrapper.orderByAsc(Order::getCreateTime);
            }
        }

        return queryWrapper;
    }

    /**
     * 转换Order实体为OrderVO（不包含订单项）
     */
    private OrderVO convertToOrderVO(Order order) {
        // 获取用户名称
        String username = null;
        if (order.getUserId() != null) {
            User user = userMapper.selectById(order.getUserId());
            if (user != null) {
                username = user.getUsername();
            }
        }

        // 获取订单项数量
        Integer itemCount = orderItemMapper.selectCount(new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderId, order.getId())).intValue();

        return OrderVO.builder()
                .id(order.getId())
                .orderNo(order.getOrderNo())
                .userId(order.getUserId())
                .username(username)
                .totalAmount(order.getTotalAmount())
                .actualAmount(order.getActualAmount())
                .paymentType(order.getPaymentType())
                .paymentTypeName(getPaymentTypeName(order.getPaymentType()))
                .paymentStatus(order.getPaymentStatus())
                .paymentStatusName(getPaymentStatusName(order.getPaymentStatus()))
                .paymentTime(order.getPaymentTime())
                .deliveryStatus(order.getDeliveryStatus())
                .deliveryStatusName(getDeliveryStatusName(order.getDeliveryStatus()))
                .deliveryTime(order.getDeliveryTime())
                .receiveTime(order.getReceiveTime())
                .expireTime(order.getExpireTime())
                .receiverName(order.getReceiverName())
                .receiverPhone(order.getReceiverPhone())
                .receiverAddress(order.getReceiverAddress())
                .remark(order.getRemark())
                .status(order.getStatus())
                .statusName(getOrderStatusName(order.getStatus()))
                .itemCount(itemCount)
                .createTime(order.getCreateTime())
                .updateTime(order.getUpdateTime())
                .canCancel(canCancelOrder(order))
                .canPay(canPayOrder(order))
                .canReceive(canReceiveOrder(order))
                .build();
    }

    /**
     * 转换Order实体为OrderVO（包含订单项）
     */
    private OrderVO convertToOrderVOWithItems(Order order) {
        OrderVO orderVO = convertToOrderVO(order);

        // 获取订单项列表
        List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderId, order.getId()));

        List<OrderItemVO> orderItemVOs = orderItems.stream()
                .map(this::convertToOrderItemVO)
                .toList();

        orderVO.setOrderItems(orderItemVOs);
        return orderVO;
    }

    /**
     * 转换OrderItem实体为OrderItemVO
     */
    private OrderItemVO convertToOrderItemVO(OrderItem orderItem) {
        return OrderItemVO.builder()
                .id(orderItem.getId())
                .productId(orderItem.getProductId())
                .productName(orderItem.getProductName())
                .productImage(orderItem.getProductImage())
                .unitPrice(orderItem.getUnitPrice())
                .quantity(orderItem.getQuantity())
                .totalPrice(orderItem.getTotalPrice())
                .canComment(true) // 已完成的订单都可以评价
                .build();
    }


    /**
     * 获取支付方式名称
     */
    private String getPaymentTypeName(Integer paymentType) {
        if (paymentType == null) return null;
        return switch (paymentType) {
            case 1 -> "微信支付";
            case 2 -> "支付宝支付";
            default -> "未知";
        };
    }

    /**
     * 获取支付状态名称
     */
    private String getPaymentStatusName(Integer paymentStatus) {
        if (paymentStatus == null) return null;
        return switch (paymentStatus) {
            case 0 -> "未支付";
            case 1 -> "已支付";
            default -> "未知";
        };
    }

    /**
     * 获取发货状态名称
     */
    private String getDeliveryStatusName(Integer deliveryStatus) {
        if (deliveryStatus == null) return null;
        return switch (deliveryStatus) {
            case 0 -> "未发货";
            case 1 -> "已发货";
            case 2 -> "已收货";
            default -> "未知";
        };
    }

    /**
     * 获取订单状态名称
     */
    private String getOrderStatusName(Integer status) {
        if (status == null) return null;
        return switch (status) {
            case 0 -> "已取消";
            case 1 -> "待支付";
            case 2 -> "待发货";
            case 3 -> "待收货";
            case 4 -> "已完成";
            case 5 -> "已过期";
            default -> "未知";
        };
    }

    /**
     * 判断订单是否可以取消
     */
    private Boolean canCancelOrder(Order order) {
        return order.getStatus() == 1; // 只有待支付状态可以取消
    }

    /**
     * 判断订单是否可以支付
     */
    private Boolean canPayOrder(Order order) {
        return order.getStatus() == 1; // 只有待支付状态可以支付
    }

    /**
     * 判断订单是否可以确认收货
     */
    private Boolean canReceiveOrder(Order order) {
        return order.getStatus() == 3; // 只有待收货状态可以确认收货
    }


    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        return "EM" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
    }

    /**
     * 恢复商品库存
     * 当订单取消或过期时，需要恢复对应商品的库存
     */
    private void restoreProductStock(Long orderId) {
        try {
            log.info("开始恢复订单商品库存: orderId={}", orderId);

            // 查询订单项
            List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>()
                    .eq(OrderItem::getOrderId, orderId)
                    .eq(OrderItem::getStatus, 1));

            // 恢复每个商品的库存
            for (OrderItem orderItem : orderItems) {
                Product product = productMapper.selectById(orderItem.getProductId());
                if (product != null) {
                    // 增加库存
                    Product updateProduct = new Product();
                    updateProduct.setId(product.getId());
                    updateProduct.setStock(product.getStock() + orderItem.getQuantity());
                    productMapper.updateById(updateProduct);

                    log.info("恢复商品库存成功: productId={}, quantity={}, newStock={}",
                            product.getId(), orderItem.getQuantity(), updateProduct.getStock());
                }
            }

            log.info("订单商品库存恢复完成: orderId={}", orderId);

        } catch (Exception e) {
            log.error("恢复订单商品库存失败: orderId={}, error={}", orderId, e.getMessage(), e);
            // 库存恢复失败不影响主流程，只记录日志
        }
    }

    /**
     * 订单商品数据内部类
     */
    private static class OrderItemData {
        private final Long productId;
        private final String productName;
        private final String productImage;
        private final BigDecimal unitPrice;
        private final Integer quantity;
        private final BigDecimal totalPrice;

        public OrderItemData(Long productId, String productName, String productImage,
                             BigDecimal unitPrice, Integer quantity, BigDecimal totalPrice) {
            this.productId = productId;
            this.productName = productName;
            this.productImage = productImage;
            this.unitPrice = unitPrice;
            this.quantity = quantity;
            this.totalPrice = totalPrice;
        }

        public Long getProductId() {
            return productId;
        }

        public String getProductName() {
            return productName;
        }

        public String getProductImage() {
            return productImage;
        }

        public BigDecimal getUnitPrice() {
            return unitPrice;
        }

        public Integer getQuantity() {
            return quantity;
        }

        public BigDecimal getTotalPrice() {
            return totalPrice;
        }
    }
}
